package cn.net.zj.scan.utils;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import cn.net.zj.scan.FKApplication;
import cn.net.zj.scan.R;

/**
 * toast显示类，可以在子线程直接调用
 * 
 */
public class ToastUtils
{
	private static Toast toast;

	public static Handler mHandler = new Handler(Looper.getMainLooper());

	public static void showToast(CharSequence text)
	{
		showToast(text, Toast.LENGTH_SHORT);
	}

	public static void showToast(final CharSequence text, final int duration)
	{
		if (Looper.myLooper() == Looper.getMainLooper())
		{
			show(text, duration);
		} else
		{
			mHandler.post(new Runnable()
			{
				@Override
				public void run()
				{
					show(text, duration);
				}
			});
		}
	}

	private static void show(CharSequence text, int duration)
	{
		if (toast != null)
		{
			toast.cancel();
		}
		View layout = LayoutInflater.from(FKApplication.getInstance()).inflate(R.layout.view_toast, null);
		TextView content = (TextView) layout.findViewById(R.id.view_toast_tv_content);
		content.setText(text);
		toast = new Toast(FKApplication.getInstance());
		toast.setDuration(duration);
		toast.setView(layout);
		toast.show();
		// toast = Toast.makeText(App.getApplication(), text, duration);
		// toast.show();

	}

	public static void showErrorTip(Throwable error, String msg)
	{

		showErrorTip(error);
	}


	public static void showErrorTip(Throwable error)
	{

		String str;
		if (error != null)
		{

			if (error instanceof JSONException)
			{
				str = "数据解析异常!";
			} else if (error instanceof UnknownHostException)
			{
				str = "无法访问的服务器地址!";
			} else if (error instanceof SocketTimeoutException)
			{
				ToastUtils.showToast("亲!您的网络不是很给力!");
				str = "服务器响应超时!";
			} else if (error instanceof ConnectTimeoutException)
			{
				ToastUtils.showToast("亲!您的网络不是很给力!");
				str = "服务器请求超时!";
			} else
			{
				str = "未知错误,请求失败!";
			}
		} else
		{
			str = "未知错误,请求失败!";
			Log.e("error_str:" ,""+ str);
		}
	}
}
